﻿using System.Text;

namespace iStudio.Structure.Extension
{
    public class BasicString
    {
        /// <summary>
        /// Converts and formats bytes to human readable string
        /// </summary>
        /// <param name="bytes">size in bytes</param>
        /// <returns>formatted string</returns>
        public static string FormatBytes(long bytes)
        {
            const int scale = 1024;
            string[] orders = new[] { "GB", "MB", "KB", "Bytes" };
            long max = (long)System.Math.Pow(scale, orders.Length - 1);

            foreach (string order in orders)
            {
                if (bytes > max)
                {
                    return string.Format("{0:##.##} {1}", decimal.Divide(bytes, max), order);
                }

                max /= scale;
            }
            return "0 Bytes";
        }

        /// <summary>
        /// Concenates string array by character
        /// </summary>
        /// <param name="stringArray">string array</param>
        /// <param name="implodeChar">character to implode with</param>
        /// <param name="count">length of array to implode to</param>
        /// <returns>concenated string</returns>
        public static string ImplodeString(string[] stringArray, char implodeChar, int count)
        {
            if (count > stringArray.Length)
            {
                count = stringArray.Length;
            }

            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < count; i++)
            {
                builder.Append(stringArray[i] + implodeChar);
            }

            string imploded = builder.ToString();

            return imploded.Substring(0, imploded.Length - 1);
        }

        /// <summary>
        /// Parse alpha numeric string (removes all other characters)
        /// </summary>
        /// <param name="str">any string</param>
        /// <returns>parsed string</returns>
        public static string ParseAlphaNumString(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return null;
            }

            StringBuilder builder = new StringBuilder();

            foreach (char t in str)
            {
                if ((char.IsLetter(t)) || (char.IsNumber(t) || (char.IsWhiteSpace(t))))
                {
                    builder.Append(t);
                }
            }

            return builder.ToString().Trim();
        }
    }
}
